#!/usr/bin/env python3
"""
FFmpeg安装脚本
检测系统环境并安装FFmpeg
"""

import os
import sys
import subprocess
import platform
import shutil
from pathlib import Path

def check_ffmpeg():
    """检查FFmpeg是否已安装"""
    try:
        result = subprocess.run(
            ['ffmpeg', '-version'], 
            capture_output=True, 
            text=True, 
            timeout=5
        )
        if result.returncode == 0:
            print("✅ FFmpeg已安装")
            print(f"版本信息: {result.stdout.split(chr(10))[0]}")
            return True
    except (FileNotFoundError, subprocess.TimeoutExpired):
        pass
    
    print("❌ FFmpeg未安装")
    return False

def install_ffmpeg_windows():
    """在Windows上安装FFmpeg"""
    print("🔧 正在为Windows系统安装FFmpeg...")
    
    # 检查是否有包管理器
    package_managers = [
        ('choco', 'choco install ffmpeg -y'),
        ('winget', 'winget install Gyan.FFmpeg'),
        ('scoop', 'scoop install ffmpeg')
    ]
    
    for manager, command in package_managers:
        if shutil.which(manager):
            print(f"使用 {manager} 安装FFmpeg...")
            try:
                result = subprocess.run(command, shell=True, check=True)
                if result.returncode == 0:
                    print("✅ FFmpeg安装成功!")
                    return True
            except subprocess.CalledProcessError:
                print(f"❌ 使用 {manager} 安装失败")
                continue
    
    # 手动安装说明
    print("""
    📋 手动安装FFmpeg步骤:
    
    1. 下载FFmpeg:
       访问 https://ffmpeg.org/download.html#build-windows
       下载Windows版本的FFmpeg
    
    2. 解压到目录:
       建议解压到 C:\\ffmpeg
    
    3. 添加到环境变量:
       将 C:\\ffmpeg\\bin 添加到PATH环境变量
    
    4. 重启终端并验证:
       运行 ffmpeg -version
    
    或者安装包管理器:
    - Chocolatey: https://chocolatey.org/install
    - Winget: 随Windows 10/11自带
    - Scoop: https://scoop.sh/
    """)
    return False

def install_ffmpeg_macos():
    """在macOS上安装FFmpeg"""
    print("🔧 正在为macOS系统安装FFmpeg...")
    
    # 检查Homebrew
    if shutil.which('brew'):
        print("使用Homebrew安装FFmpeg...")
        try:
            subprocess.run(['brew', 'install', 'ffmpeg'], check=True)
            print("✅ FFmpeg安装成功!")
            return True
        except subprocess.CalledProcessError:
            print("❌ Homebrew安装失败")
    
    # 检查MacPorts
    if shutil.which('port'):
        print("使用MacPorts安装FFmpeg...")
        try:
            subprocess.run(['sudo', 'port', 'install', 'ffmpeg'], check=True)
            print("✅ FFmpeg安装成功!")
            return True
        except subprocess.CalledProcessError:
            print("❌ MacPorts安装失败")
    
    print("""
    📋 手动安装FFmpeg步骤:
    
    1. 安装Homebrew (推荐):
       /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
       
    2. 使用Homebrew安装FFmpeg:
       brew install ffmpeg
    
    或者从官网下载:
    https://ffmpeg.org/download.html#build-mac
    """)
    return False

def install_ffmpeg_linux():
    """在Linux上安装FFmpeg"""
    print("🔧 正在为Linux系统安装FFmpeg...")
    
    # 检测Linux发行版
    distro_commands = [
        # Ubuntu/Debian
        ('apt', 'sudo apt update && sudo apt install -y ffmpeg'),
        # CentOS/RHEL/Fedora
        ('yum', 'sudo yum install -y ffmpeg'),
        ('dnf', 'sudo dnf install -y ffmpeg'),
        # Arch Linux
        ('pacman', 'sudo pacman -S ffmpeg'),
        # openSUSE
        ('zypper', 'sudo zypper install ffmpeg'),
        # Alpine
        ('apk', 'sudo apk add ffmpeg'),
    ]
    
    for manager, command in distro_commands:
        if shutil.which(manager):
            print(f"使用 {manager} 安装FFmpeg...")
            try:
                result = subprocess.run(command, shell=True, check=True)
                if result.returncode == 0:
                    print("✅ FFmpeg安装成功!")
                    return True
            except subprocess.CalledProcessError:
                print(f"❌ 使用 {manager} 安装失败")
                continue
    
    print("""
    📋 手动安装FFmpeg步骤:
    
    Ubuntu/Debian:
    sudo apt update && sudo apt install ffmpeg
    
    CentOS/RHEL:
    sudo yum install epel-release
    sudo yum install ffmpeg
    
    Fedora:
    sudo dnf install ffmpeg
    
    Arch Linux:
    sudo pacman -S ffmpeg
    
    或从源码编译:
    https://ffmpeg.org/download.html#build-linux
    """)
    return False

def main():
    """主函数"""
    print("🎵 Echo Role TTS语音系统 - FFmpeg安装器")
    print("=" * 50)
    
    # 检查FFmpeg是否已安装
    if check_ffmpeg():
        print("🎉 FFmpeg已可用，无需安装!")
        return True
    
    # 根据系统类型安装
    system = platform.system().lower()
    
    if system == 'windows':
        success = install_ffmpeg_windows()
    elif system == 'darwin':  # macOS
        success = install_ffmpeg_macos()
    elif system == 'linux':
        success = install_ffmpeg_linux()
    else:
        print(f"❌ 不支持的操作系统: {system}")
        return False
    
    if success:
        # 验证安装
        print("\n🔍 验证安装...")
        if check_ffmpeg():
            print("🎉 FFmpeg安装并验证成功!")
            return True
        else:
            print("❌ FFmpeg安装后验证失败，请检查PATH环境变量")
            return False
    else:
        print("\n⚠️  自动安装失败，请按照上述说明手动安装FFmpeg")
        return False

if __name__ == '__main__':
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n⏹️  安装过程被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 安装过程中发生错误: {e}")
        sys.exit(1) 